package cn.micai.base.lambda;

import java.util.Random;

/**
 * 描述：Java – Generate random integers in a range
 * <p>  在一个范围内生成随机整数
 *
 * 我们将向您展示三种方法来生成一个范围内的随机整数
 *
 *  1.java.util.Random.nextInt
 *  2.Math.random
 *  3.java.util.Random.ints (Java 8)
 *
 * @author: 赵新国
 * @date: 2018/6/22 15:08
 */
public class GenerateRandomIntergersInaRangeExample {

    public static void main(String [] args) {

        for (int i=0; i<10; i++) {
            /*int randomNumberInRange = getRandomNumberInRange(5, 10);
            System.out.println(randomNumberInRange);*/
            /*int randomNumberInRange = getRandomNumberInRange2(16, 20);
            System.out.println(randomNumberInRange);*/
            int randomNumberInRange = getRandomNumberInRange3(100000, 999999);
            System.out.println(randomNumberInRange);
        }

    }

    // 1. java.util.Random
    public static int getRandomNumberInRange(int min, int max) {
        if (min >= max) {
            throw new IllegalArgumentException("max must be greater than min");
        }
        Random r = new Random();
        return r.nextInt((max -min) + 1) + min;
    }

    // 2. Math.random
    public static int getRandomNumberInRange2(int min, int max) {
        if (min >= max) {
            throw new IllegalArgumentException("max must be greater than min");
        }
        return (int) (Math.random()*((max-min)+1))+min;
    }

    // 3. Java 8 Random.ints
    public static int getRandomNumberInRange3(int min, int max) {
        Random r = new Random();
//        return r.ints(min, (max + 1)).findFirst().getAsInt();
        return r.ints(min, (max + 1)).limit(1).findFirst().getAsInt();
    }


}
